﻿using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ProdService;
using UI.Filters;
using ViewModels.JsonResult;
using ViewModels.Shared;
using static Global.Const;

namespace UI.ApiControllers
{
    [TypeFilter(typeof(EndDbContext))]
    [ValidateModelState]
    [ApiController]
    public class BaseController : ControllerBase
    {
        protected UserService userService;
        protected PhoneService phoneService;
        public BaseController(
            UserService userService = null,
            PhoneService phoneService = null)
        {
            this.userService = userService;
            this.phoneService = phoneService;
        }

        protected WithError checkSMS(PhoneModel model)
        {
            Phone phone = phoneService.GetBy(model.Number);
            return checkSMS(model, phone);
        }

        protected WithError checkSMS(PhoneModel model, Phone phone)
        {
            WithError result = new();
            if (phone == null)
            {
                result.Errors.Add(nameof(model.Number), "* 电话号码不存在");
            }
            else if (phone.ExpiredTime < DateTime.Now)
            {
                result.Errors.Add(nameof(model.CheckCode), "* 短信验证码过期");
            }
            else if (phone.CheckCode != model.CheckCode)
            {
                result.Errors.Add(nameof(model.CheckCode), "* 短信验证码错误");
            }//else nothing

            return result;
        }
        protected WithError checkCaptcha(string captcha)
        {
            return checkCaptcha(new CaptchaModel { Captcha = captcha });
        }

        protected WithError checkCaptcha(ICaptchaModel model)
        {
            WithError result = new();

            string inSession = HttpContext.Session.GetString(SessionKey.Captcha),
                errorKey = nameof(model.Captcha);

            if (string.IsNullOrEmpty(inSession))
            {
                result.Errors.Add(errorKey, ErrorMessages.Expired);
            }
            else if (inSession.Trim() != model.Captcha.ToUpper())
            {
                result.Errors.Add(errorKey, ErrorMessages.Wrong);
            }//else continue

            return result;
        }

    }
}
